import 'package:bruno/bruno.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/RouteAct.dart';
import '../../Main/MyWallet/DepositManagement.dart';
import '../../http/NoLoadingPostApi.dart';
import '../../http/api.dart';
import '../TMSGoodsAddView.dart';
import '../TMSOrderList.dart';
import 'DispatchList.dart';
import 'TMSOrderDetial.dart';

class NoSchedulingList extends StatefulWidget {
  const NoSchedulingList({super.key});

  @override
  State<NoSchedulingList> createState() => _NoSchedulingListState();
}

class _NoSchedulingListState extends State<NoSchedulingList> {
  List dataList=[];
  int pageNum=1;
  String timeTitle="下单时间";
  String customerStratTime="";
  String customerEndTime="";
  String createStratTime="";
  String createEndTime="";
  String  schedulingStr="";
  String customerName="";
  String trackingNumber="";
  String deliveryNumber="";
  String reasonStr="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getOrderListAction();
  }
  void getOrderListAction(){
    NoLoadingApiManager.postData(
      context,
      "api/tms/order/page",
      {
        "status":0,
        "companyId":"1",
        "current":pageNum,
        "size":20,
        "customerOrderDateStart":customerStratTime,
        "customerOrderDateEnd":customerEndTime,
        "orderCreateDateStart":createStratTime,
        "orderCreateDateEnd":createEndTime,
        "customerOrderNum":trackingNumber,
        "customerLoadOrderNum":deliveryNumber,
        "searchKey":customerName,
      },
          (responseData) async {
        setState(() {
          if(pageNum==1) {
            dataList = responseData['data']['records'];
          }else{
            if(responseData['data']['records'].isNotEmpty){
              dataList.addAll( responseData['data']['records']);
            }else{
              pageNum=pageNum-1;
            }
          }
        });

      },
    );
  }
  void onReachBottom() {
    setState(() {
      pageNum=pageNum+1;

    });

  }


  void _onRefresh() {
    setState(() {
      pageNum=1;

    });

    // 在这里可以执行加载更多数据的逻辑
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      body:Column(
        children: [
          Container(
            padding: EdgeInsets.only(top: 4.h,left: 10.w,right: 10.w),
            height: 35.h,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                  child: Row(
                    children: [
                      Text(timeTitle,style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                      Icon(Icons.keyboard_arrow_down,color: MyColors.authTipColor,size: 14,),
                    ],),
                  onTap: ()async{
                    final result= await showModalBottomSheet(
                      context: context,
                      builder: (BuildContext context) {
                        return dataTimeSheet(type: 1,
                        );
                      },
                    );
                    if (result != null) {
                      setState(() {
                        setState(() {
                          timeTitle=result;
                          customerStratTime=timeTitle.substring(0, 10);
                          customerEndTime=timeTitle.substring(timeTitle.length - 10, timeTitle.length);
                        });
                        getOrderListAction();
                      });
                    }
                  },
                ),
                GestureDetector(
                  child:  Row(
                    children: [
                      Text("筛选",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      Image.asset("lib/Images/OrderList/找货筛选icon.png",width: 15.w,height: 15.h,)
                    ],
                  ),
                  onTap: ()async{
                   final result=await Navigator.push( context, FadeRoute(page:TMSFiltering()));
                   if(result!=null){
                     setState(() {
                       createStratTime=result[0].substring(0, 10);
                       createEndTime=result[0].substring(timeTitle.length - 10, timeTitle.length);
                       schedulingStr=result[4];
                       customerName=result[1];
                       trackingNumber=result[2];
                       deliveryNumber=result[3];
                     });
                     getOrderListAction();
                   }
                  },
                )
              ],
            ),
          ),
          Expanded(child:
          EasyRefresh(
              header:
              ClassicHeader(
                dragText: '下拉刷新',
                armedText: '准备释放',
                readyText: '加载中...',
                processingText: '加载中...',
                processedText: '刷新成功',
                noMoreText: '暂无更多',
                failedText: '刷新失败',
                messageText: '刷新时间 %T',
              ),
              footer: ClassicFooter(
                dragText: '加载更多',
                armedText: '准备释放',
                readyText: '加载中...',
                processingText: '加载中...',
                processedText: '加载成功',
                noMoreText: '暂无更多',
                failedText: '加载失败',
                messageText: '加载时间 %T',
              ),
              onRefresh: _onRefresh,
              onLoad:dataList.length>pageNum*20-1?onReachBottom:null,
              child:
              Container(
                  color: Color.fromRGBO(248, 248, 248, 1),
                  child:  ListView(
                      children: [
                        Container(
                            // margin: EdgeInsets.only(top: 8.h),
                            height:screenSize.height-256.h,
                            child:
                            dataList.isEmpty?
                            BrnAbnormalStateWidget(
                              img: Image.asset(
                                'lib/Images/OrderList/找货暂无货源.png',
                                scale: 3.0,
                              ),
                              content: '您的账号暂无订单',
                            ): ListView.separated(
                              shrinkWrap:true,
                              itemCount: dataList.length,
                              itemBuilder: (BuildContext context, int index) {
                                return GestureDetector(
                                  onTap: (){ Navigator.push( context, FadeRoute(page:TMSOrderDetial(dataMap: dataList[index],)));},
                                  child: Container(
                                    margin: EdgeInsets.only(left: 8.w,right: 8.w),
                                    padding: EdgeInsets.only(top: 10.h,right: 10.w,bottom: 10.h,left: 10.w),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(10))),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text(dataList[index]['orderNum'],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                            Text(dataList[index]['consignorInfo']['name'].toString(),style: TextStyle(color: MyColors.textColor,fontSize: 11.sp),),
                                          ],
                                        ),
                                        SizedBox(height: 4.h,),
                                        Text(dataList[index]['consigneeInfo']==null?"未指定客户":dataList[index]['consigneeInfo']['name'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                                        SizedBox(height: 4.h,),
                                        Text("${dataList[index]['cargoInfo']['name'].toString()}丨${dataList[index]['cargoInfo']['packageType'].toString()}丨${dataList[index]['cargoInfo']['weight'].toString()}${dataList[index]['cargoInfo']['weightUnit'].toString()}",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                                        SizedBox(height: 4.h,),
                                        Row(
                                          children: [
                                            Image.asset("lib/Images/OrderList/装icon.png",width: 13.w,height: 13.h,),
                                            SizedBox(width: 4.w,),
                                            Container(
                                              constraints: BoxConstraints(
                                                maxWidth:screenSize.width-60.w,

                                              ),
                                              child:   Text(dataList[index]['consignorInfo']['place']['address'],style: TextStyle(color: Colors.black,fontSize: 13.sp),overflow: TextOverflow.ellipsis,),
                                            ),
                                          ],
                                        ),
                                        Image.asset("lib/Images/OrderList/垂直虚线.png",width:13.w ,height:8.h,),

                                        Row(
                                          children: [
                                            Image.asset("lib/Images/OrderList/卸icon.png",width: 13.w,height: 13.h,),
                                            SizedBox(width: 4.w,),
                                            Container(
                                              constraints: BoxConstraints(
                                                maxWidth:screenSize.width-60.w,
                                              ),
                                              child:   Text(dataList[index]['consigneeInfo']['place']['address'],style: TextStyle(color: Colors.black,fontSize: 13.sp),overflow: TextOverflow.ellipsis,),
                                            ),
                                          ],
                                        ),
                                        Divider(height: 20.h,color: MyColors.backgreyColor,),
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.end,
                                          children: [

                                            GestureDetector(
                                              child:   BrnTagCustom.buildBorderTag(
                                                tagText: '调度',
                                                textColor:  MyColors.themeColor,
                                                borderColor: MyColors.themeColor,
                                                borderWidth: 1,
                                                fontSize: 13.sp,
                                                tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                                textPadding: EdgeInsets.only(left: 10.w,right: 10.w,top: 2.h,bottom: 2.h),
                                              ),
                                            ),
                                            // SizedBox(width: 4.w,),
                                            // GestureDetector(
                                            //   child:   BrnTagCustom.buildBorderTag(
                                            //     tagText: '修改',
                                            //     textColor:  MyColors.themeColor,
                                            //     borderColor: MyColors.themeColor,
                                            //     borderWidth: 1,
                                            //     fontSize: 13.sp,
                                            //     tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                            //     textPadding: EdgeInsets.only(left: 10.w,right: 10.w,top: 2.h,bottom: 2.h),
                                            //   ),
                                            // ),
                                            SizedBox(width: 4.w,),
                                            GestureDetector(
                                              child:   BrnTagCustom.buildBorderTag(
                                                tagText: '标记异常',
                                                textColor:  MyColors.themeColor,
                                                borderColor: MyColors.themeColor,
                                                borderWidth: 1,
                                                fontSize: 13.sp,
                                                tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                                textPadding: EdgeInsets.only(left: 10.w,right: 10.w,top: 2.h,bottom: 2.h),
                                              ),
                                              onTap: (){
                                                showDialog(
                                                  barrierDismissible: false,
                                                  context: context,
                                                  builder: (BuildContext context) {
                                                    return BrnDialog(
                                                      titleText: dataList[index]['state']=="NORMAL"?"标记异常":"取消异常标记",
                                                      contentWidget:BrnInputText(
                                                        maxHeight: 100,
                                                        minHeight: 100,
                                                        minLines:2,
                                                        maxLength: 200,
                                                        bgColor: MyColors.backgreyColor,
                                                        textString:reasonStr ?? '',
                                                        textInputAction: TextInputAction.newline,
                                                        // maxHintLines: 20,
                                                        hint: '其他原因',
                                                        padding: EdgeInsets.fromLTRB(20, 10, 20, 14),
                                                        onTextChange: (text) {
                                                          print(text);

                                                          setState(() {
                                                            reasonStr = text;
                                                          });
                                                        },
                                                        onSubmit: (text) {
                                                          print(text);
                                                        },
                                                      ),
                                                      actionsWidget: [
                                                        TextButton(
                                                          onPressed: () {
                                                            Navigator.pop(context);
                                                          },
                                                          child: Text("取消",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                                        ),
                                                        TextButton(
                                                          onPressed: () {
                                                            ApiManager.postData(
                                                              context,
                                                              'api/user/shpr/user/searchAirCarList',
                                                              {
                                                                "id": dataList[index]['id'],
                                                                "state": dataList[index]['state']=="NORMAL"?"ABNORMAL":"NORMAL",
                                                                "stateReason": reasonStr,
                                                              },
                                                                  (responseData) {
                                                                BrnToast.show("操作成功", context);
                                                                Navigator.pop(context);
                                                                getOrderListAction();
                                                              },
                                                            );
                                                          },
                                                          child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                                        ),

                                                      ],
                                                    );
                                                  },
                                                );
                                              },
                                            ),

                                          ],
                                        )
                                      ],
                                    ),
                                  ),
                                );
                              },  separatorBuilder: (context, index) { //自定义分割线
                              return   Container(
                                height: 8.h,
                              );
                            },
                            )
                        )
                      ]
                  )
              )
          ) , ),
          Container(
            color: Colors.white,
            height: 80.h,
            width: screenSize.width,
            padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 10.h,bottom:40.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                BrnSmallMainButton(
                  title: '创建订单',
                  bgColor: MyColors.themeColor,
                  textColor: Colors.white,
                  fontSize: 14.sp,
                  radius: 30,
                  width: 80.w,
                  onTap: () {
                    Navigator.push( context, FadeRoute(page:TMSGoodsAddView()));
                  },
                ),
                SizedBox(width: 10.w,),
                BrnSmallMainButton(
                  title: '配载',
                  bgColor: MyColors.themeColor,
                  textColor: Colors.white,
                  fontSize: 14.sp,
                  radius: 30,
                  width:60.w,
                  onTap: () {
                    Navigator.push( context, FadeRoute(page:DispatchList()));
                  },
                ),




              ],
            ),
          ),
        ],
      )

    );
  }

}
